package com.lzy.article.controller;

import com.lzy.api.config.RabbitMQConfig;
import com.lzy.api.config.RabbitMQDelayConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("producer")
public class RabbitMQController {

    @Autowired
    public RabbitTemplate rabbitTemplate;

    @GetMapping("/hello")
    public Object hello() {

        // 向 EXCHANGE_ARTICLE 发送一条消息，并且指定相应的路由规则
//        rabbitTemplate.convertAndSend(
//                RabbitMQConfig.EXCHANGE_ARTICLE,
//                "article.download", "去GridFS下载文章的HTML吧~~");
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_ARTICLE,
                "article.publish.download.do", "1001~~");

        rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_ARTICLE,
                "article.success.do", "1002~~");

        rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_ARTICLE,
                "article.play", "1003~~");
        return "OK";
    }

    @GetMapping("/delay")
    public Object delay() {

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置持久
                message.getMessageProperties()
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                // 设置延迟的时间，单位毫秒
                message.getMessageProperties().setDelay(5000);
                return message;
            }
        };

        // 发送延迟消息
        rabbitTemplate.convertAndSend(
                RabbitMQDelayConfig.EXCHANGE_DELAY,
                "delay.demo",
                "这是一条延迟消息~",
                messagePostProcessor);

        System.out.println("生产者发送延迟消息：" + new Date());

        return "OK";
    }


}


